package com.voole.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.voole.dao.BaseDao;
import com.voole.dao.SysActionDao;
import com.voole.dao.SysResourceDao;
import com.voole.dao.SysRoleDao;
import com.voole.dao.SysUserDao;
import com.voole.dao.SysUserRoleDao;
import com.voole.entity.SysAction;
import com.voole.entity.SysResource;
import com.voole.entity.SysRole;
import com.voole.entity.SysUser;
import com.voole.entity.SysUserRole;
import com.voole.service.ISysUserService;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class SysUserServiceImpl implements ISysUserService {

	@Autowired
	private BaseDao baseDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private SysRoleDao sysRoleDao;
	@Autowired
	private SysResourceDao sysResourceDao;
	@Autowired
	private SysActionDao sysActionDao;
	 
	/**
	 * 根据用户名查询是否存在该用户 For SpringSecurity
	 * @param account 用户名
	 * @return 用户名对应的用户实体
	 */
	public SysUser getSysUserByAccount(String account) throws Exception {
		return sysUserDao.getSysUserByAccount(account);
	}

	/**
	 * 根据当前登录用户获取用户对应的权限角色、菜单以及功能 For SpringSecurity
	 * @param user 当前登录用户
	 */
	public Collection<GrantedAuthority> getAuthorities(SysUser user) throws Exception {
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();  
        
        if("admin".equals(user.getAccount())){//如果账号是admin，特殊处理，给予所有权限
        	List<SysRole> allRoleList = sysRoleDao.getList();
        	for(SysRole sysRole : allRoleList){
        		authList.add(new SimpleGrantedAuthority(sysRole.getRole()));//举例：sysRole.getRole() = ROLE_ADMIN
        	}
        }else{//如果账号不是admin，根据user.id查找拥有权限
        	List<SysRole> roleList = sysRoleDao.getListByUserId(user.getId());
        	for(SysRole sysRole : roleList){
        		authList.add(new SimpleGrantedAuthority(sysRole.getRole()));
        	}
        }
        
        return authList;
	}

	/**
	 * 得到所有菜单资源，先从缓存中读取，如果没有从数据库中重新加载 For SpringSecurity
	 */
	public Map<String, Collection<ConfigAttribute>> getResourceMap() throws Exception {
		Map<String, Collection<ConfigAttribute>> resourceMap = new HashMap<String, Collection<ConfigAttribute>>();

		//三级目录
		List<SysResource> resources = sysResourceDao.getList();
		for(SysResource resource : resources){
			Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
			
			List<SysRole> roleList = sysRoleDao.getList();
			for(SysRole role :roleList){
				configAttributes.add(new SecurityConfig(role.getRole()));
			}
			//所有三级目录每个人都可以访问（因为里面的table，功能都有四级目录决定，所以三级目录无所谓）
			resourceMap.put(resource.getUrl(), configAttributes);
		}
		
		//四级目录(功能)
		List<SysAction> actions = sysActionDao.getList();
		for (SysAction action : actions) {
			Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
			
			List<String> columnRoleList = sysRoleDao.getColumnRoleByActionId(action.getId());//根据四级目录ID 查找 对应权限，放入集合
			for(String columnRole :columnRoleList){
				configAttributes.add(new SecurityConfig(columnRole));
			}
			configAttributes.add(new SecurityConfig("ROLE_ADMIN"));// <- 每一个菜单都可以被管理员权限访问
			
			//四级目录 URL 和 权限放入集合
			resourceMap.put(action.getUrl(), configAttributes);
		}

		return resourceMap;
	}

	/**
	 * 用户列表（分页）
	 */
	public Map<String, Object> findByPage(String start, String length) throws Exception {
		//计算分页行数
		Integer end = Integer.parseInt(start) + Integer.parseInt(length);
		//获取分页内容总数
		Integer count = sysUserDao.getCount();
		//获取分页当前内容
		String sql = "SELECT * FROM sys_user ORDER BY account ASC LIMIT "+Integer.parseInt(start)+", "+end;
		List<Map<String, Object>> list = baseDao.getList(sql);
		for(Map<String, Object> userMap : list){
			List<String> roleName = sysUserRoleDao.getRoleNameList(Integer.parseInt(userMap.get("id").toString()));
			userMap.put("roleNames", roleName.toString());
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data", list);
		map.put("recordsTotal", list.size());//pageSize
		map.put("recordsFiltered", count);//count
		return map;
	}

	/**
	 * 新增用户 和 对应权限
	 */
	public Map<String, Object> addUserAndRole(String account, String name, String password, String roleIds) throws Exception {
		//保存用户
		SysUser su = new SysUser();
		su.setAccount(account);
		su.setName(name);
		su.setPassword(password);
		su.setCreatetime(new Date());
		su.setUpdatetime(new Date());
		su.setStatus(0);
		sysUserDao.addSysUser(su);
		Integer userId = su.getId();
		
		//保存权限
		String[] roleIdArray = roleIds.split(",");
		if(roleIdArray.length==0){
			List<String> list = Arrays.asList(roleIdArray);
			for(String roleId :list){
				SysUserRole sur = new SysUserRole();
				sur.setUserid(userId);
				sur.setRoleid(Integer.parseInt(roleId));
				sysUserRoleDao.addSysUserRole(sur);
			}
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("msg", "操作成功");
		return result;
	}

	/**
	 * 获取用户 以及 拥有权限List
	 *（根据用户id）
	 */
	public SysUser getSysUser(String userId) throws Exception {
		SysUser su = sysUserDao.getSysUser(Integer.parseInt(userId));
		
		List<SysRole> roleList = sysRoleDao.getListByUserId(Integer.parseInt(userId));
		
		su.setRoleList(roleList);
		
		return su;
	}

}
